<?php

require_once '../include/common.inc.php';
require_once '../include/upfile.class.php';

if (!checkAdmin()) {
    header("LOCATION:index.php");
    exit;
}

$menu_index = 1;
$page_title = 'JANSEN';
$guide_message = 'Product | Basic Infomation | List Product';
$out_ary = array();
$tmp_ary = array();
$ppp = 20;
$page_show = '';
$key = "Enter code or name";

getMyParam('action');
getMyParam('key');
getMyParam('edits');
getMyParam('view');

if ($action != "")
{
    if ($action == 'add' || $action == 'edit') {
		 
		 //add by martin 		 
		getMyParam('finishshownzh');		
       // getMyParam('fabricshownzh');		
        //getMyParam('leathershownzh');
		//getMyParam('fabricshown');
        //getMyParam('leathershown');
		getMyParam('fabric_id');
		getMyParam('leather_id');
		
        getMyParam('marbleshownzh');      
        getMyParam('namezh');
		getMyParam('commentzh');
		getMyParam('pinfozh');
		 
        getMyParam('finishshown');
     
        getMyParam('marbleshown');
        getMyParam('code');	
        getMyParam('name');
        getMyParam('length');
        getMyParam('height');
        getMyParam('width');
        getMyParam('length2');
        getMyParam('height2');
        getMyParam('width2');
        getMyParam('cbm');
        getMyParam('cuft');
        getMyParam('up_pic');   
        getMyParam('up_small_pic');   
        getMyParam('price_1');
        getMyParam('price_2');
        getMyParam('price_3');
        getMyParam('new_flag');
        //getMyParam('clearance_flag');
        getMyParam('hidden_flag');
        getMyParam('comment');
        getMyParam('inventory_id');
        getMyParam('category_id');
        getMyParam('category_seq');
        //getMyParam('inventory_seq');
		getMyParam('qty_ary');
		getMyParam('sp_ary');
		getMyParam('sp2_ary');
		getMyParam('pinfo');
		getMyParam('selCollection');
		getMyParam('selSetting');
		getMyParam('seeting_seq');		
		getMyParam('selStyle');
		getMyParam('selFinishes');
		getMyParam('related_id');
		getMyParam('seq');
		getMyParam('auction');
		getMyParam('discount');
		getMyParam('interval');
		getMyParam('time_start');
		getMyParam('time_end');
		getMyParam('is_soldout');
		
		//deal post value
        $change_col = '';
        $file_name = '';
        if($_FILES['up_pic']['size'] > 0 && trim($_FILES['up_pic']['name']) != ""){
            $upfile = new uploadFile($_FILES['up_pic']);
            $upfile->setFileName2($_FILES['up_pic']['name']);
            $upfile->setFileType(array('image/pjpeg', 'image/gif', 'image/jpeg'));
            $upfile->setAcceptOverwrite(1);//1:
            $upfile->setStoreDir(JANSEN_ROOT.'zh/attachments/');
            $upfile->setMaxSize(1024*1024*2);
            if (!$upfile->save()) {
                echo "<script>alert('" . $upfile->error_msg . "');location.href='p_product.php';</script>";
                exit;
            }
            $file_name = $upfile->fileName;
            $change_col .= ", `pic` = '$file_name'";
        }
        $file_name2 = '';
        if($_FILES['up_small_pic']['size'] > 0 && trim($_FILES['up_small_pic']['name']) != ""){
            $upfile = new uploadFile($_FILES['up_small_pic']);        
            $upfile->setFileName2($_FILES['up_small_pic']['name']);
            $upfile->setFileType(array('image/pjpeg', 'image/gif', 'image/jpeg'));
            $upfile->setAcceptOverwrite(1);
            $upfile->setStoreDir(JANSEN_ROOT.'zh/attachments/');
            $upfile->setMaxSize(1024*1024*2);
            if (!$upfile->save()) {
				echo "<script>alert('" . $upfile->error_msg . "');location.href='p_product.php';</script>";
                exit;
            }
            $file_name2 = $upfile->fileName;
            $change_col .= ", `small_pic` = '$file_name2'";
        }
		// clearance sale
		$discount = $discount / 100;
		$time_start = strtotime($time_start);
		$time_end = strtotime($time_end);

        if ($action == 'add') {
            if ($name != "" && $code != "") 
			{               
$pinfozh= htmlentities($pinfozh,ENT_QUOTES,"UTF-8");
$pinfo= htmlentities($pinfo,ENT_QUOTES,"UTF-8");
$sql = "INSERT INTO `product` (`code`,`name`, `length`, `height`, `width`, `length2`, `height2`, `width2`, `cbm`, `cuft`, `small_pic`, `pic`, `price_1`, `price_2`, `price_3`, `new_flag`, `hidden_flag`, `comment`,`finishshown`,`fabric_id`,`leather_id`,`marbleshown`,`info`,`collection_id`,`style_id`,`finish_id`,`auction`,`discount`,`interval`,`time_start`,`time_end`,`is_soldout`) VALUES ('$code', '$name', '$length', '$height', '$width', '$length2', '$height2', '$width2', '$cbm', '$cuft', '$file_name2', '$file_name', '$price_1', '$price_2', '$price_3', '$new_flag', '$hidden_flag', '$comment','$finishshown','$fabric_id','$leather_id','$marbleshown','$pinfo','$selCollection','$selStyle','$selFinishes', '$auction', '$discount', '$interval', '$time_start', '$time_end', '$is_soldout')";
                $db->query($sql);
                $product_id = $db->insert_id();

	
                //product_inventory
                if (!empty($inventory_id)) {
                    foreach($inventory_id as $k1=>$v1) {
                        !isset($sp2_ary[$v1]) && $sp2_ary[$v1] = 0;
                        !isset($sp_ary[$v1]) && $sp_ary[$v1] = 0;
                        if (!isset($qty_ary[$v1]) || ($qty_ary[$v1]) == '') {
                            $qty_ary[$v1] = 0;
                        }

                        $sql_1 = "INSERT INTO `product_inventory` (`product_id`, `inventory_id`, `qty`, `special_price`, `special_price2`) VALUES ('$product_id', '$v1', $qty_ary[$v1], '" . $sp_ary[$v1] . "', '" . $sp2_ary[$v1] . "')";
                        $db->query($sql_1);
                    }
                }
				//product setting
				if (!empty($selSetting)) {
				$sqld = "DELETE  FROM  `product_p_setting` WHERE `product_id`=".$product_id;							
				$db->query($sqld);	
				
                    foreach($selSetting as $k2=>$v2) {
                        $sql_2 = "INSERT INTO `product_p_setting` (`product_id`, `setting_id`, `seq`) VALUES ('".$product_id."', '$v2', '" . $seeting_seq[$k2] . "')";
						//echo $k2;
                      $db->query($sql_2);
                    }
                 }
                //product_category
                if (!empty($category_id)) {
                    foreach($category_id as $k2=>$v2) {
                        $sql_2 = "INSERT INTO `product_category` (`product_id`, `category_id`, `seq`) VALUES ('$product_id', '$v2', '" . $category_seq[$v2] . "')";
                        $db->query($sql_2);
                    }
                }		
				// related item
				foreach($related_id as $k => $v)
				{
					$sql = "INSERT INTO `p_related`(`pid`,`related_id`,`seq`) values('$product_id',$v,$seq[$k])";
					$db->query($sql);
					$sql = "SELECT MAX(seq) FROM `p_related` WHERE pid = $v";
					$rs = $db->get_one();
					$seq2 = isset($rs[0])?$rs[0]:0;
					$seq2++;
					$sql = "INSERT INTO `p_related`(`pid`,`related_id`,`seq`) values($v,'$product_id',$seq2)";
					$db->query($sql);
				}
            }
           goFromPage();
		   
		   } elseif ($action == 'edit')
		    {    	
            getMyParam('pid');

            if (is_numeric($pid) && $pid > 0 && $code != "") {
				if(($_FILES['up_pic']['size'] > 0 && trim($_FILES['up_pic']['name']) != "") || ($_FILES['up_small_pic']['size'] > 0 && trim($_FILES['up_small_pic']['name']) != "")){
                  
                    $sql = "SELECT `pic`, `small_pic` FROM `product` WHERE `id` = '" . $pid . "'";
                    $rs = $db->get_one($sql);
					if (trim($_FILES['up_pic']['name']) != "" && $_FILES['up_pic']['name'] != $rs['pic'] ) {
						delPicture($rs['pic']);
					}
					if (trim($_FILES['up_small_pic']['name']) != "" && $_FILES['up_small_pic']['name'] != $rs['small_pic'] ) {
						delPicture($rs['small_pic']);
					}
                }
$pinfozh= htmlentities($pinfozh,ENT_QUOTES,"UTF-8");
$pinfo= htmlentities($pinfo,ENT_QUOTES,"UTF-8");
$sql = "UPDATE `product` SET
`code` = '$code', 
`name` =  '$name', 
`finishshown` =  '$finishshown',
`fabric_id` =  '$fabric_id',
`leather_id` =  '$leather_id',
`marbleshown` =  '$marbleshown',  
`length` =  '$length', 
`height` =  '$height', 
`width` =  '$width', 
`length2` =  '$length2', 
`height2` =  '$height2', 
`width2` =  '$width2', 
`cbm` =  '$cbm',
`cuft` =  '$cuft' " . $change_col . ",                              
`price_1` =  '$price_1', 
`price_2` =  '$price_2', 
`price_3` =  '$price_3', 
`new_flag` =  '$new_flag', 
`hidden_flag` =  '$hidden_flag',
`comment` = '$comment',
`info` = '$pinfo',
`collection_id` = '$selCollection',
`style_id` = '$selStyle',
`finish_id` = '$selFinishes',
`auction` = '$auction',
`discount` = '$discount',
`interval` = '$interval',
`time_start` = '$time_start',
`time_end` = '$time_end',
`is_soldout` = '$is_soldout'
WHERE `id` = '$pid'";
//`setting_id` = $selSetting,
                $db->query($sql);				
                $sql_del_1 = "DELETE FROM `product_inventory` WHERE `product_id` = '$pid'";
                $sql_del_2 = "DELETE FROM `product_category` WHERE `product_id` = '$pid'";
				$sql_del_3 = "DELETE FROM `product_p_setting` WHERE `product_id` = '$pid'";
                $db->query($sql_del_1) && $db->query($sql_del_2)&&$db->query($sql_del_3);

                //product_inventory
                if (!empty($inventory_id)) {
                    foreach($inventory_id as $k1=>$v1)
					 {              
						
						if (!isset($qty_ary[$v1]) || ($qty_ary[$v1]) == '') {
							$qty_ary[$v1] = 0;
						}
						if (!isset($sp_ary[$v1]) || ($sp_ary[$v1]) == '') {
							$sp_ary[$v1] = 0;
						}
						if (!isset($sp2_ary[$v1]) || ($sp2_ary[$v1]) == '') {
							$sp2_ary[$v1] = 0;
						}

                        $sql_1 = "INSERT INTO `product_inventory` (`product_id`, `inventory_id`, `qty`, `special_price`, `special_price2`) VALUES ('$pid', '$v1', $qty_ary[$v1], '" . $sp_ary[$v1] . "', '" . $sp2_ary[$v1] . "')";
                       
						$db->query($sql_1);
                    }
                }

                //product_category
                if (!empty($category_id)) {
                    foreach($category_id as $k2=>$v2) {
							if($category_seq[$v2]=="") $category_seq[$v2]=0;
							if(is_numeric($category_seq[$v2]))
							{
								$sql_2 = "INSERT INTO `product_category` (`product_id`, `category_id`, `seq`) VALUES ('$pid', '$v2', '" . $category_seq[$v2] . "')";
								$db->query($sql_2);
							}
                    }
                }
				
				
				//setting 
				if (!empty($selSetting))
				 {				
                    foreach($selSetting as $k2=>$v2) {
                        $sql_2 = "INSERT INTO `product_p_setting` (`product_id`, `setting_id`, `seq`) VALUES ('".$pid."', '$v2', '" . $seeting_seq[$k2] . "')";						
                    $db->query($sql_2);				
					 
                    }
                 }	
            }
			 // related item
			foreach($related_id as $k => $v)
			{
				$sql = "select * from p_related where pid=$pid AND related_id=$v";
				$query = $db->query($sql);
				$rs = $db->fetch_array($query);
				if(empty($rs['pid']))
				{
					$sql = "INSERT INTO `p_related`(`pid`,`related_id`,`seq`) values('$pid',$v,$seq[$k])";
					$db->query($sql);
					$sql = "SELECT MAX(seq) as seq FROM `p_related` WHERE pid = $v";
					$rs = $db->get_one($sql);
					$seq2 = isset($rs['seq'])?$rs['seq']:0;
					$seq2++;
					$sql = "INSERT INTO `p_related`(`pid`,`related_id`,`seq`) values($v,'$pid',$seq2)";
					$db->query($sql);
				}
				else
				{
					$sql = "UPDATE `p_related` SET seq = $seq[$k] WHERE pid = $pid AND related_id = $v";
					$db->query($sql);
				}
			}
        
		  $sta="&act=2";
		  goFromPagePro('',$sta);
		}
        //goFromPage();
		//$sta="&act=2";
		//goFromPagePro('',$sta);
    }
    if ($action == 'del') {
        getMyParam('pid');
        if (is_numeric($pid) && $pid > 0) {
            $sql_1 = "DELETE FROM `product` WHERE `id` = '" . $pid . "'";
            $sql_2 = "DELETE FROM `product_inventory` WHERE `product_id` = '" . $pid . "'";
            $sql_3 = "DELETE FROM `product_category` WHERE `product_id` = '" . $pid . "'";
			$sql_4 = "DELETE FROM `product_p_setting` WHERE `product_id` = '".$pid."'";
			$sql_5 = "DELETE FROM `p_related` WHERE `pid` = '".$pid."'";
			$sql_6 = "DELETE FROM `p_related` WHERE `related_id` = '".$pid."'";
            $db->query($sql_1) && $db->query($sql_2) && $db->query($sql_3)&& $db->query($sql_4)&& $db->query($sql_5)&& $db->query($sql_6);
        }
        goFromPage();
    }
    //header("LOCATION:p_product.php");
	header("LOCATION:index.php");
}
getMyParam('iid');
getMyParam('cid');
$page_url = 'p_product.php?';
$sql_where = "WHERE 1=1";

if (is_numeric($cid) || is_numeric($iid)) {
    $page_url = 'p_product.php?cid=' . $cid . '&iid=' . $iid . '&';

	if ($iid >0 && $cid > 0) {
		$aryIn = get_category(0);
		//ǰIDڵIDַ
		$str_sub_cateid = GetCategoryTreeIDS($aryIn,$cid,false);
		echo "cids:".$str_sub_cateid;		
		
		$sql = "SELECT i.`product_id` FROM `product_inventory` i , `product_category` c WHERE  i.inventory_id='$iid' AND c.product_id=i.product_id AND category_id IN(".$str_sub_cateid.");";
        $query = $db->query($sql);
        while($rs1 = $db->fetch_array($query)) {
            $tmp_ary[] = $rs1['product_id'];
        }
    } else if ($iid >0) {
        $sql = "SELECT product_id FROM product_inventory WHERE inventory_id='$iid'";
        $query = $db->query($sql);
        while($rs1 = $db->fetch_array($query)) {
            $tmp_ary[] = $rs1['product_id'];
        }
    } else if ($cid >0) {
		$aryIn = get_category(0);
		//ǰIDڵIDַ
			$str_sub_cateid = GetCategoryTreeIDS($aryIn,$cid,false);
		
		$sql = "SELECT product_id FROM product_category WHERE category_id IN(".$str_sub_cateid.");";
        $query = $db->query($sql);
        while($rs1 = $db->fetch_array($query)) {
            $tmp_ary[] = $rs1['product_id'];
        }
    }

    if (!empty($tmp_ary)) {
        $tmp_str = implode(",", $tmp_ary);
        $sql_where .= " AND `id` IN (" . $tmp_str . ")";
    } elseif ($iid >0 || $cid > 0) {
        $sql_where .= " AND `id` =0";
    }
}

if ($key != 'Enter code or name' && trim($key) != '') {
    $page_url .= 'key=' . $key . '&';
    $sql_where .= " AND (`code` LIKE '%$key%' OR `name` LIKE '%$key%')";
}

$sql = "SELECT `id` FROM `product` $sql_where";
$query = $db->query($sql);
$sql_all_num = $db->num_rows($query);

// *** page code start ***
getMyParam('page');
$page = empty($page) || !ispage($page) ? 1 : $page;
$start_limit = ($page - 1) * $ppp;
if($start_limit > $sql_all_num) {
    $start_limit = 0;
    $page = 1;
}
// *** page code end ***


$sql = "SELECT `id`, `name`,`code`, `price_1`, `price_2`, `price_3`, `new_flag`, `hidden_flag`, `auction` FROM `product` $sql_where ORDER BY `id` DESC LIMIT $start_limit, $ppp";
$query = $db->query($sql);

while($rs = $db->fetch_array($query)) {
    if ($key != 'Enter code or name' && trim($key) != '') {
        $rs['name'] = str_replace($key, "<font color=red>$key</font>", $rs['name']);
        $rs['code'] = str_replace($key, "<font color=red>$key</font>", $rs['code']);
		
		
    }
	$rs['pinfozh']=html_entity_decode($rs["pinfozh"],ENT_QUOTES,"UTF-8");
	$rs['pinfo']=html_entity_decode($rs["pinfo"],ENT_QUOTES,"UTF-8");	
	$rs['pages']=$page_url."edits=".$rs['id']."&page=".$page."&"; 
    $out_ary[] = $rs;
}
$page_show = getPageStr($sql_all_num, $page, $ppp, $page_url);





//  inventory, categor
$sql = "SELECT `id`, `name` FROM `inventory` ORDER BY `seq` ASC";
$query = $db->query($sql);
$inventory_select_ary[0] = "Select...";
while($rs = $db->fetch_array($query)) {
    $inventory_select_ary[$rs['id']] = $rs['name'];
}


function GetProductCateOptions($ary,$l)
{
	$s='';
	$sp = '';
	for($i=0;$i<$l;$i++)
	{
		$sp .= '&nbsp;&nbsp;&nbsp;&nbsp;';	
	}
	foreach($ary as $k => $v)
	{
		$s.= '<option value="'.$k.'">'.$sp.$v["name"].'</option>';	
		if($v["sub_cate"]!=null && count($v["sub_cate"])>0)
		{
			$s.=GetProductCateOptions($v["sub_cate"],$l+1);	
		}
	}
	return $s;
}
$strProductCateOptions = GetProductCateOptions($_categories,0);


$disstatus='style="display:none"';
//if(!isset($action)||$action=='edit')

if(!isset($act)||$act!="2")
{
	if(isset($edits)&&$edits!=""&&isset($view)&&$view==1)
	{
	   if($action!="edit")
		$disstatus="";
		$id=$edits;
		$sql = "SELECT `id`, `name`,`namezh` ,`seq`, `type` FROM `inventory` ORDER BY `seq`";
		$query = $db->query($sql);
		while($rs = $db->fetch_array($query)) {
			$inventory_ary[] = $rs;
		}
		$inventory_ary_num = count($inventory_ary);
	
		// select inventory
		$inventory_have_selected_ary = array();
		$inventory_qty_ary = array();
		$inventory_sp_ary = array();
		$inventory_sp2_ary = array();
		
		$sql = "SELECT `inventory_id`, `qty`, `special_price`, `special_price2` FROM `product_inventory` WHERE `product_id` = '$id'";
		$query = $db->query($sql);
		while($rs = $db->fetch_array($query)) {
			$inventory_have_selected_ary[] = $rs['inventory_id'];
			$inventory_qty_ary[$rs['inventory_id']] = $rs['qty'];
			$inventory_sp_ary[$rs['inventory_id']] = $rs['special_price'];
			$inventory_sp2_ary[$rs['inventory_id']] = $rs['special_price2'];
		}
	
	
		// select category
		$category_have_selected_ary = array();
		$category_seq_value_ary = array();  
		
		$sql = "SELECT `category_id`, `seq` FROM `product_category` WHERE `product_id` = '$id'";
		$query = $db->query($sql);
		while($rs = $db->fetch_array($query)) {
			$category_have_selected_ary[] = $rs['category_id'];
			$category_seq_value_ary[$rs['category_id']] = $rs['seq'];
		} 
	
	
		$inventor_select_str = '';
		for($i=0; $i<$inventory_ary_num; $i++){
			$checked2 = "";
			$disabled2 = "disabled";
			if (in_array($inventory_ary[$i]['id'], $inventory_have_selected_ary)) {
				$checked2 = "checked";
				$disabled2 = "";
			}
	
			
			$inventory_qty_ary[$inventory_ary[$i]['id']] = isset($inventory_qty_ary[$inventory_ary[$i]['id']]) ? $inventory_qty_ary[$inventory_ary[$i]['id']] : 0;
			$inventory_sp_ary[$inventory_ary[$i]['id']] = isset($inventory_sp_ary[$inventory_ary[$i]['id']]) ? $inventory_sp_ary[$inventory_ary[$i]['id']] : 0;
			$inventory_sp2_ary[$inventory_ary[$i]['id']] = isset($inventory_sp2_ary[$inventory_ary[$i]['id']]) ? $inventory_sp2_ary[$inventory_ary[$i]['id']] : 0;
	
			// 
			if ($inventory_ary[$i]['type'] == 1) {
				$ovr_desc = 'Ovr ';
				$hk_sp = ' HK <input id="sp2_' . $inventory_ary[$i]['id'] . '" value="' . $inventory_sp2_ary[$inventory_ary[$i]['id']] . '" type="text" name="sp2_ary[' . $inventory_ary[$i]['id'] . ']" size="5"  ' . $disabled2 . ' />';
			} else {
				$ovr_desc = '';
				$hk_sp = '<input id="sp2_' . $inventory_ary[$i]['id'] . '" value="0" type="hidden" name="sp2_ary[' . $inventory_ary[$i]['id'] . ']"  ' . $disabled2 . ' />';
			}
			
			$inventor_select_str .= '<tr class="tbcontent1">
						  <td align="left"><input type="checkbox" name="inventory_id[]" value="' . $inventory_ary[$i]['id'] . '" onchange="if ( this.checked==true){qty_' . $inventory_ary[$i]['id'] . '.disabled=false;sp_' . $inventory_ary[$i]['id'] . '.disabled=false;sp2_' . $inventory_ary[$i]['id'] . '.disabled=false;} else {qty_' . $inventory_ary[$i]['id'] . '.disabled=true;sp_' . $inventory_ary[$i]['id'] . '.disabled=true;sp2_' . $inventory_ary[$i]['id'] . '.disabled=true;}" ' . $checked2 . ' />' . $inventory_ary[$i]['name'] . '</td>
						  <td align="center"><input id="qty_' . $inventory_ary[$i]['id'] . '" value="' . $inventory_qty_ary[$inventory_ary[$i]['id']] . '" type="text" name="qty_ary[' . $inventory_ary[$i]['id'] . ']" size="3"  ' . $disabled2 . ' /></td>
						  <td align="center">' . $ovr_desc . '<input id="sp_' . $inventory_ary[$i]['id'] . '" value="' . $inventory_sp_ary[$inventory_ary[$i]['id']] . '" type="text" name="sp_ary[' . $inventory_ary[$i]['id'] . ']" size="5"  ' . $disabled2 . ' /> ' . $hk_sp . '</td>
						</tr>';
		}
	
		$category_select_str = '<tr class="tbheader">
						  <td align="left">Category/Sub Category</td>
						  <td align="center">Product Sequence</td>
						</tr>';
		$category_select_str	.= GetProductCate($_categories,0,$category_have_selected_ary,$category_seq_value_ary);			
	  
		$sql = "SELECT * FROM `product` WHERE `id` = '$id'";
		$rs = $db->get_one($sql);
	 
		if ($rs['new_flag'] == 1) {
			$new_selected_yes = "selected";
			$new_selected_no = "";
		} else {
			$new_selected_yes = "";
			$new_selected_no = "selected";
		}
	
		if ($rs['hidden_flag'] == 1) {
			$hidden_flag_selected_yes = "selected";
			$hidden_flag_selected_no = "";
		} else {
			$hidden_flag_selected_yes = "";
			$hidden_flag_selected_no = "selected";
		}
	
		$img_show = "";
		if ($rs['pic'] != "") {
			$img_show = '<img src="../zh/attachments/' . $rs['pic'] . '" border=0><br>';
		}
		$img_show2 = "";
		if ($rs['small_pic'] != "") {
			$img_show2 = '<img src="../zh/attachments/' . $rs['small_pic'] . '" border=0><br>';
		}
		
		//Setting
		$sql = "SELECT *  FROM `product_p_setting` WHERE  `product_id` = '".$id."'";
		$hasarr=array();
		$seqarr=array();	
		$querys = $db->query($sql);	
		
		while($rss = $db->fetch_array($querys))
		{
		
		  $hasarr[]=$rss["setting_id"];
		  $seqarr[$rss["setting_id"]]=isset($rs["seq"])?$rs["seq"]:0;
		}	
		$hasset ='';	
		$sql = "SELECT `id`, `name`  FROM `p_setting` WHERE `ispublish` = 1";
		$strSetting = '';
		$query = $db->query($sql);
		$ids=0;
		
		while($rsSetting = $db->fetch_array($query))
		{
		   $ids++;
			if(in_array($rsSetting['id'],$hasarr))
			{		
				$check = 'checked="checked"';	
				$disa="";		
			}			
			else
			{
				$disa='disabled="disabled"';
				$check = "";
			}
			  //$strSetting .= '<option value="'.$rsSetting["id"].'"'.$strSelected.'>'.$rsSetting["name"].'</option>';
			  $strSetting.='<tr class="tbcontent1"><td><input  onchange="if ( this.checked==true){seetingseq_'.$ids.'.disabled=false;} else {seetingseq_'.$ids.'.disabled=true;}" '.$check.' type="checkbox" value="'.$rsSetting["id"].'" name="selSetting[]" id=input_"'.$ids.'" /><label     for=input_"'.$ids.'">'.$rsSetting["name"].'</label></td><td><input id="seetingseq_'.$ids.'" type="text" '.$disa.' name="seeting_seq[]" size="3" value="'.$seqarr[$rsSetting["id"]].'"></td></tr>';
			  
		}
	
		//Collection
		$sql = "SELECT `id`, `name`  FROM `p_collection` WHERE `ispublish` = 1 order by orderindex";
		$strCollection = '';
		$query = $db->query($sql);
		while($rsCollection = $db->fetch_array($query))
		{
			if($rsCollection["id"]==$rs["collection_id"])
				$strSelected = " selected";
			else
			$strSelected = "";
			$strCollection .= '<option value="'.$rsCollection["id"].'"'.$strSelected.'>'.$rsCollection["name"].'</option>';
		}
	
		//Finishes
		$sql = "SELECT `id`, `name`  FROM `p_finish_set`";
		$strFinishes = '';
		$query = $db->query($sql);
		while($rsFinishes = $db->fetch_array($query))
		{
			if($rsFinishes["id"]==$rs["finish_id"])
				$strSelected = " selected";
			else
				$strSelected = "";
			$strFinishes .= '<option value="'.$rsFinishes["id"].'"'.$strSelected.'>'.$rsFinishes["name"].'</option>';
		}
		
		// Clearance Sale
		$strdiscount = '';
		for($i=1;$i<51;$i++)
		{
			if($i == $rs["discount"] * 100)
				$strSelected = " selected";
			else
				$strSelected = "";
			$strdiscount .= '<option value="'.$i.'"'.$strSelected.'>'.$i.'</option>';	
		}
		$strinterval = '';
		for($i=1;$i<51;$i++)
		{
			if($i == $rs["interval"])
				$strSelected = " selected";
			else
				$strSelected = "";
			$strinterval .= '<option value="'.$i.'"'.$strSelected.'>'.$i.'</option>';	
		}
		$time_start = ! empty($rs['time_start']) ? date('Y-m-d',$rs['time_start']) : '';
		$time_end = ! empty($rs['time_end']) ? date('Y-m-d',$rs['time_end']) : '';
		$strsoldout = '<option value="1"'.($rs['is_soldout'] == 1 ? ' selected':'').'>Yes</option>';
		$strsoldout .= '<option value="0"'.($rs['is_soldout'] == 0 ? ' selected':'').'>No</option>';
	
		//Style / Priod
		$sql = "SELECT `id`, `name`  FROM `p_style` WHERE `ispublish` = 1";
		$strStyle = '';
		$query = $db->query($sql);
		while($rsStyle = $db->fetch_array($query))
		{
			if($rsStyle["id"]==$rs["style_id"])
				$strSelected = " selected";
			else
				$strSelected = "";
			$strStyle .= '<option value="'.$rsStyle["id"].'"'.$strSelected.'>'.$rsStyle["name"].'</option>';
		}
		
		
		//fabrics
		$fabrics="";
		$sql = "SELECT * FROM `p_fabric` ORDER BY `seq`";
		$query = $db->query($sql);
		while($rsf = $db->fetch_array($query)) 
		{
		    $sl="";
		    if(!empty($rsf['name']))
			{
			   if($rsf['id']==$rs['fabric_id'])
                   $sl='selected="selected"';
			   $fabrics.='<option '.$sl.'  value="'.$rsf['id'].'" >' .$rsf['name'].'</option>';
			}
		}
		
		
		
		
		//leather
		$leathers="";
		$sql = "SELECT * FROM `p_leather` ORDER BY `seq`";
		$query = $db->query($sql);
		while($rsl = $db->fetch_array($query)) 
		{
		 $sl="";
		   if(!empty($rsl['name']))
		   {       
		          if($rsl['id']==$rs['leather_id'])
                   $sl='selected="selected"';
			  $leathers.='<option '.$sl.' value="'.$rsl['id'].'">' .$rsl['name'].'</option>';
			}
		}
		
		// related item
		$related_str = "";
		$sql = "SELECT pr.*,p.code,p.name FROM `p_related` as pr join `product` as p on pr.related_id = p.id WHERE pr.pid = $id ORDER BY `seq`";
		$query = $db->query($sql);
		while($rsrelated = $db->fetch_array($query)) 
		{
			$related_str .= '<tr class="tbcontent1" id="tr_'.$rsrelated['related_id'].'"><td><input type="hidden" name="related_id[]" value="'.$rsrelated['related_id'].'"/>'.$rsrelated['code'].'</td><td>'.$rsrelated['name'].'</td><td><input type="text" class="text" name="seq[]" size="5" value="'.$rsrelated['seq'].'"/></td><td><a href="javascript:;" onclick="remove('.$rsrelated['pid'].','.$rsrelated['related_id'].')" title="Remove">Remove</a></td></tr>';
		}
	}
	
}
 $out_str ='<form action="p_product.php" method="post" name="formedit" enctype="multipart/form-data"><table width="100%" border="0" cellspacing="1" cellpadding="1" id="formedit">
              <tr valign="vtop"> 
                <td>Web code nr :</td>
                <td>
                  <input type="text" class="text" name="code" value="' . $rs['code'] . '">	  
                  <input name="action" type="hidden" value="edit">
				  <input name="view" type="hidden" value="2">
                  <input name="pid" type="hidden" value="' . $id . '">
                </td>
              </tr>
			
              <tr valign="vtop"> 
                <td>Name :</td>
                <td><textarea class="text" name="name" cols="40" rows="2"  >' . htmlentities($rs['name']) . '</textarea></td>
              </tr>			  
              <tr valign="vtop"> 
                <td>Small Picture :<br/> (Size:113*113 Pixel)</td>
                <td>' . $img_show2 . '<input type="file" class="text" name="up_small_pic" size=50></td>
              </tr>
              <tr valign="vtop"> 
                <td>Picture :<br/>(Size:850*850 Pixel)</td>
                <td>' . $img_show . '<input type="file" class="text" name="up_pic" size=50></td>
              </tr>
			  
              <tr valign="vtop"> 
                <td>Finish Shown :</td>
                <td><input type="text" class="text" name="finishshown" value="' . $rs['finishshown'] . '"> </td>
              </tr>
			  
			   <tr valign="vtop"> 
                <td>Fabric Shown :</td>
                <td><select id="fabricshown" name="fabric_id" >
				<option value="0" >Select--</option>' .$fabrics. '</select>				
				</td>
              </tr>	
			  	
			  <tr valign="vtop"> 
                <td>Leather Shown :</td>
                <td>
				<select id="leathershown" name="leather_id" >
				<option value="0">Select--</option>
				    '.$leathers.'
				</select>
				</td>
              </tr>	
			   <tr valign="vtop"> 
                <td>Marble Shown :</td>
                <td><input type="text" class="text" name="marbleshown" value="' . $rs['marbleshown'] . '"> </td>
              </tr>
              <tr valign="vtop"> 
                <td>Depth :</td>
                <td><input type="text" class="text" name="length" value="' . $rs['length'] . '"> CM</td>
              </tr>
              <tr valign="vtop"> 
                <td>Width :</td>
                <td><input type="text" class="text" name="width" value="' . $rs['width'] . '"> CM</td>
              </tr>
              <tr valign="vtop"> 
                <td>Height :</td>
                <td><input type="text" class="text" name="height" value="' . $rs['height'] . '"> CM</td>
              </tr>
              
              <tr valign="vtop"> 
                <td>Depth :</td>
                <td><input type="text" class="text" name="length2" value="' . $rs['length2'] . '"> INCH</td>
              </tr>
              <tr valign="vtop"> 
                <td>Width :</td>
                <td><input type="text" class="text" name="width2" value="' . $rs['width2'] . '"> INCH</td>
              </tr>
              <tr valign="vtop"> 
                <td>Height :</td>
                <td><input type="text" class="text" name="height2" value="' . $rs['height2'] . '"> INCH</td>
              </tr>
              
              <tr valign="vtop"> 
                <td>Cbm :</td>
                <td><input type="text" class="text" name="cbm" value="' . $rs['cbm'] . '"></td>
              </tr>             
              <tr valign="vtop"> 
                <td>Cuft :</td>
                <td><input type="text" class="text" name="cuft" value="' . $rs['cuft'] . '"></td>
              </tr>  
              
              <tr valign="vtop"> 
                <td>Price : </td>
                <td>                
                   <input type="text" class="text" name="price_3" size="10" value="' . $rs['price_3'] . '"  > EUR(€)<br>
                  
                </td>
              </tr>
			<tr><td>Auction:</td><td><select class="select" name="auction" id="sel_auction" onchange="auction_change()"><option value="0">No</option><option value="1"'.($rs['auction']==1?' selected="selected"':'').'>Yes</option></select></td></tr>
			<tr class="clearance"><td>Discount:</td><td><select class="select" name="discount"><option value="0">Select--</option>'.$strdiscount.'</select>%</td></tr>
			<tr class="clearance"><td>Interval:</td><td><select class="select" name="interval"><option value="0">Select--</option>'.$strinterval.'</select>Days</td></tr>
			<tr class="clearance"><td>Start Date:</td><td><input type="text" class="text" id="time_start" name="time_start" size="20" value="'.$time_start.'"  ></td></tr>
			<tr class="clearance"><td>End Date:</td><td><input type="text" class="text" id="time_end" name="time_end" size="20" value="'.$time_end.'"  ></td></tr>
			<tr class="clearance"><td>Sold Out:</td><td><select class="select" name="is_soldout"><option value="0">Select--</option>'.$strsoldout.'</select></td></td></tr>     
              <tr valign="vtop"> 
                <td>New Item :</td>
                <td>							  
                  <select class="select" name="new_flag"  >
                  <option value=1 ' . $new_selected_yes . '>Yes</option><option value=0 ' . $new_selected_no . '>No</option></select> 
                </td>
              </tr>
              
              <tr valign="vtop"> 
                <td>Hidden in product :</td>
                <td>							  
                  <select class="select" name="hidden_flag"  >
			<option value=1 ' . $hidden_flag_selected_yes . '>Yes</option><option value=0 ' . $hidden_flag_selected_no . '>No</option></select> 
			</td>
			</tr>
			<tr valign="vtop">
			<td>Collection:</td>
			<td><select class="select" name="selCollection"><option value="0">Select--</option>'.$strCollection.'</select>
                    </td>
                </tr>
                <tr valign="vtop">
                    <td valign="top">Setting:
                    </td>
                    <td>
              <table width="100%" border="0" cellspacing="1" cellpadding="1" class="tb">         
			'.$strSetting.'
			</table>
			</td>
			</tr>
			<tr valign="vtop">
			<td>Style / Period:
			</td>
			<td><select class="select" name="selStyle"><option value="0">Select--</option>'.$strStyle.'</select>
			</td>
			</tr>
			<tr valign="vtop">
			<td>Finish categories
			</td>
			<td><select class="select" name="selFinishes"><option value="0">Select--</option>'.$strFinishes.'</select>
			</td>
			</tr>
			<tr valign="vtop">
			<td>
			Product info:</td>
			<td>
			<textarea class="text" style="width:700px;height:300px;visibility:hidden;" cols="40" name="pinfo" rows="4">' . stripslashes(html_entity_decode($rs["info"],ENT_QUOTES,"UTF-8")). '</textarea>
			</td>
			</tr>
			<tr valign="vtop"> 
			<td>Description :</td>
                <td><textarea class="text" name="comment" cols="40" rows="4"  >' . stripslashes($rs['comment']) . '</textarea></td>
              </tr>
			              
              <tr valign="vtop"> 
                <td>Inventory :</td>
                <td>
                  <table width="100%" border="0" cellspacing="1" cellpadding="1" class="tb">
                    <tr class="tbheader">
                      <td align="left">Inventory</td>
                      <td align="center">Available Qty</td>
                      <td align="center">Special Price</td>
                    </tr>					
                    ' . $inventor_select_str . '
                  </table>     
                </td>
              </tr>
              <tr valign="vtop"> 

                <td>category :</td>
                <td>
                    <table width="100%" border="0" cellspacing="1" cellpadding="1" class="tb">
                    ' . $category_select_str . '
                    </table>
                </td>
              </tr>			              
              <tr valign="vtop"> 
                <td>Related Items :</td>
                <td><table cellspacing="1" cellpadding="1" border="0">
                    <tbody><tr> 
                      <td><input type="text" onfocus="this.value=\'\'" value="Enter code ..." size="20" name="related_code" class="text" id="related_code"></td>
                      <td><input type="image" src="../images/admin/bt_add.gif" onclick="add_item();return false;" name="image" id="btn_add_item"></td>
			          <td><img width="30" src="../images/admin/shim.gif"></td>
                    </tr>
                  </tbody></table>
				  <table class="tb" width="100%" cellspacing="1" cellpadding="1" border="0">
				  <tbody id="item_list"><tr class="tbheader"><td width="20%">code</td><td width="50%">name</td><td width="15%">seq</td><td width="15%">remove</td></tr>'.$related_str.'</tbody></table>				  
				  </td>
              </tr>      
              <tr valign="vtop"> 
                <td align="right" colspan=2>
                  <input type="image" src="../images/admin/bt_cancel.gif" width="78" height="23" onclick="adminEditCancel(\'edit_area\')"> 
                  <input type="image" src="../images/admin/bt_save.gif" width="76" height="22" onclick="formedit.submit"> 
                </td>
              </tr>
              <tr height=30> 
                <td colspan=2></td>
              </tr>
            </table>
          </form>';



$debug = 1;
debuginfo();

include_once(JANSEN_ROOT . 'admin/menu_list.php');
require_once PrintEot('a_header');
require_once PrintEot('a_p_product');
require_once PrintEot('a_footer');

?>